import json
import os
import time

TASKS_FILE = "tasks.json"

def load_tasks():
    if os.path.exists(TASKS_FILE):
        with open(TASKS_FILE, 'r', encoding='utf-8') as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return []
    return []

def save_tasks(tasks):
    with open(TASKS_FILE, 'w', encoding='utf-8') as f:
        json.dump(tasks, f, indent=4, ensure_ascii=False)

def view_tasks(tasks):
    print("\n--- 你的待办事项 ---")
    if not tasks:
        print("太棒了！当前没有待办任务。")
    else:
        for i, task in enumerate(tasks, 1):
            status_symbol = "✓" if task['completed'] else " "
            print(f"{i}. [{status_symbol}] {task['task']}")
    print("--------------------")

def add_task(tasks):
    task_description = input("请输入新的任务内容: ")
    if task_description.strip():
        new_task = {'task': task_description, 'completed': False}
        tasks.append(new_task)
        save_tasks(tasks)
        print(f"✅ 任务 '{task_description}' 已添加。")
    else:
        print("❌ 错误：任务内容不能为空。")

def complete_task(tasks):
    view_tasks(tasks)
    if not tasks:
        return # 如果没有任务，直接返回
    try:
        task_num_str = input("请输入要标记为【完成】的任务编号: ")
        task_num = int(task_num_str)
        if 1 <= task_num <= len(tasks):
            task_index = task_num - 1
            if not tasks[task_index]['completed']:
                tasks[task_index]['completed'] = True
                save_tasks(tasks)
                print(f"🎉 任务 '{tasks[task_index]['task']}' 已标记为完成。")
            else:
                print(f"🤔 任务 '{tasks[task_index]['task']}' 已经是完成状态了。")
        else:
            print(f"❌ 错误：无效的编号。请输入 1 到 {len(tasks)} 之间的数字。")
    except ValueError:
        print("❌ 错误：请输入一个有效的数字编号。")

def delete_task(tasks):
    view_tasks(tasks)
    if not tasks:
        return # 如果没有任务，直接返回    
    try:
        task_num_str = input("请输入要【删除】的任务编号: ")
        task_num = int(task_num_str)

        if 1 <= task_num <= len(tasks):
            task_index = task_num - 1
            removed_task = tasks.pop(task_index)
            save_tasks(tasks)
            print(f"🗑️ 任务 '{removed_task['task']}' 已被删除。")
        else:
            print(f"❌ 错误：无效的编号。请输入 1 到 {len(tasks)} 之间的数字。")
    except ValueError:
        print("❌ 错误：请输入一个有效的数字编号。")

def main():
    tasks = load_tasks()    
    while True:
        # 打印主菜单
        print("\n===== 命令行 To-Do List 应用 =====")
        print("1. 查看所有任务")
        print("2. 添加新任务")
        print("3. 标记任务为完成")
        print("4. 删除任务")
        print("5. 退出程序")
        print("==================================")        
        choice = input("请选择一个操作 (1-5): ")        
        if choice == '1':
            view_tasks(tasks)
        elif choice == '2':
            add_task(tasks)
        elif choice == '3':
            complete_task(tasks)
        elif choice == '4':
            delete_task(tasks)
        elif choice == '5':
            print("感谢使用，再见！👋")
            time.sleep(1) # 暂停1秒，让用户看到消息
            break # 退出 while 循环，结束程序
        else:
            print("❌ 无效的输入，请输入 1 到 5 之间的数字。")
        input("\n按 Enter 键继续...")

if __name__ == "__main__":
    main()